//
//  TCP4Socket.m
//  SimpleServer
//
//  Created by Sean Breid on 12/16/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "TCP4Socket.h"

#include "tcp4.h"


struct SocketImpl {
    Socket* socket;
};

@implementation TCP4Socket
    
    -(id)init
    {
        
        self = [super init];
        
        if(self)
        {
            Sockets = new SocketImpl;
        }
        
        Sockets->socket = new TCP4();
        
        return self;
    }

    -(id)initWithPort:(NSInteger) port
    {
    
        self = [self init];//create a tcp4 socket
    
        Sockets->socket->Bind(port);//bind the socket to port
    
        return self;
    
    
    }

    -(id)initWithSocket: (struct SocketImpl*) sockStruct
    {
    
        self = [super init];
        Sockets = sockStruct; 

        return self;
    }

    -(void)Listen
    {
        Sockets->socket->Listen();
    }
    
    -(TCP4Socket*)Accept{
        
        struct SocketImpl* tempSock = new SocketImpl;
        
        tempSock->socket = Sockets->socket->Accept();
    
        TCP4Socket* connectedSock = [[TCP4Socket alloc ]initWithSocket: tempSock ];
        
        return connectedSock;
    }

    -(void)SendWithBuffer: (NSData*) buffer ofSize: (NSInteger) length{
        //this seems like its not being initialized
        char* sendBuffer = new char[length];
        memset(sendBuffer, 0 , length);
        [buffer getBytes:sendBuffer length:length];
        Sockets->socket->Send(sendBuffer, length);
        
    
    }

    -(id)ReceiveBufferOfSize: (NSInteger) length
    {
        
        char receiveBuffer[length];
        memset(receiveBuffer, 0, length);
        Sockets->socket->Receive(receiveBuffer, length);
        NSData* buffer = [NSData dataWithBytes:receiveBuffer length:length];
        
        return buffer;
        
        
    }


    -(void)ConnectToAddress: (NSString*) address onPort: (NSInteger) port{
    
        char* addr = (char*)[address UTF8String];
        
        Sockets->socket->Connect(addr, port);
        
    }

    -(void)Close{
        Sockets->socket->Close();
    
    }


@end
